//
//  PopoverAnimator.swift
//  SwiftSina
//
//  Created by Jason Ding on 16/8/18.
//  Copyright © 2016年 Jason Ding. All rights reserved.
//

import UIKit

class PopoverAnimator: NSObject {
    var isPresented : Bool = false

}

// MARK:- 自定义转场的代理
extension PopoverAnimator : UIViewControllerTransitioningDelegate{
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        return RRPresentationController(presentedViewController: presented, presentingViewController: presenting)
    }
    
    // 自定义弹出动画
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

// MARK:- UIViewControllerAnimatedTransitioning
extension PopoverAnimator : UIViewControllerAnimatedTransitioning{
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    // 转场的上下文, 获取 弹出和消失的view
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        isPresented ? animationForPresentedView(transitionContext) : animationForDismissedView(transitionContext)
        
        
    }
    
    private func animationForPresentedView(transitionContext: UIViewControllerContextTransitioning){
        
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        
        transitionContext.containerView()?.addSubview(toView)
        
        toView.transform = CGAffineTransformMakeScale(1.0, 0.0)
        toView.layer.anchorPoint = CGPointMake(0.5, 0)
        UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: {
            toView.transform = CGAffineTransformIdentity
            
        }) { (_) in
            
            // 必须告诉上下文, 已经完成了动画
            transitionContext.completeTransition(true)
        }
    }
    
    private func animationForDismissedView(transitionContext: UIViewControllerContextTransitioning){
        // 1.获取消失的View
        let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey)
        
        // 2.执行动画
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            dismissView?.transform = CGAffineTransformMakeScale(1.0, 0.00001)
        }) { (_) -> Void in
            dismissView?.removeFromSuperview()
            // 必须告诉转场上下文你已经完成动画
            transitionContext.completeTransition(true)
        }
    }
}
